package com.mankiw.springboot_mankiw.Service;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mankiw.springboot_mankiw.pojo.User;
import com.mankiw.springboot_mankiw.pojo.dto.UserDto;
import com.mankiw.springboot_mankiw.repository.UserRepository;

@Service //spring 的bean
public class UserService implements IUserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public User add(UserDto user) {
        User userPojo = new User();
        //拷贝对象
        BeanUtils.copyProperties(user, userPojo);
        //save方法 add可以用，update也可以用，根据是否有id判断是update还是add
        //返回User对象
        return userRepository.save(userPojo);
    }

    @Override
    public User getUser(Integer userId) {
        var value = userRepository.findById(userId);
        return userRepository.findById(userId).orElseThrow(() -> {
            throw new IllegalArgumentException("user not exist");
        });
    }

    @Override
    public User edit(UserDto user) {
        User userPojo = new User();
        BeanUtils.copyProperties(user, userPojo);
        return userRepository.save(userPojo);
    }

    @Override
    public void delete(Integer userId) {
        userRepository.deleteById(userId);
    }
}
